import webapp2
import urllib
import jinja2
import os
import json

from google.appengine.ext import ndb


#Defines the entity model.
class Record(ndb.Model):
    key = ndb.StringProperty(indexed = True)
    lat = ndb.FloatProperty(indexed = False)
    lon = ndb.FloatProperty(indexed = False)

def GetKey(placa, fecha, hora):
  date = ""
  for c in fecha:
    if c.isdigit():
      date = date + c
  ms = ""
  for c in hora:
    if c.isdigit():
      ms = ms + c

  if len(ms) != 6:
    # in case hour does not contains seconds
    assert len(ms) == 4
    ms = ms + "00"
  # ads ms.
  ms = ms + "000"
  return placa.upper() + "#" + date + ms

class QueryData:
    placa = ""
    inicio_fecha = ""
    inicio_hora = ""
    fin_fecha = ""
    fin_hora = ""
    key_inicio = ""
    key_fin = ""

    def __init__(self, request):
      self.placa = request.get('placa')
      self.inicio_fecha = request.get('inicio_fecha')
      self.inicio_hora = request.get('inicio_hora')
      self.fin_fecha = request.get('fin_fecha')
      self.fin_hora = request.get('fin_hora')
      self.key_inicio = GetKey(self.placa, self.inicio_fecha, self.inicio_hora)
      self.key_fin = GetKey(self.placa, self.fin_fecha, self.fin_hora)


class DisplayAnswer(webapp2.RequestHandler):
    def post(self):
      query = QueryData(self.request)
      jinja_environment = self.jinja_environment
      template = jinja_environment.get_template("/display_result.html")
      self.response.out.write(template.render({'query': query}))

    @property
    def jinja_environment(self):
      jinja_environment = jinja2.Environment(
          loader=jinja2.FileSystemLoader(
            os.path.join(os.path.dirname(__file__),
              '../views'
              )
            )
          )
      return jinja_environment

class Retriever(webapp2.RequestHandler):
    def post(self):
      data = json.loads(self.request.body)
      key_inicio = data["beg_key"]
      key_fin = data["end_key"]
      query = Record.query(Record.key >= key_inicio)
      records =  query.fetch(5000);
      dict_records = []
      # Returns unique values.
      if len(records) > 0 :
        for i in range(0, len(records)-1):
          if i == 0 or records[i].key != records[i-1].key :
              dict_records.append(records[i].to_dict())
      self.response.out.write(json.dumps(({'records': dict_records})))

class QueryForm(webapp2.RequestHandler):
    def get(self):
      jinja_environment = self.jinja_environment
      template = jinja_environment.get_template("/query_form.html")
      self.response.out.write(template.render({}))

    @property
    def jinja_environment(self):
      jinja_environment = jinja2.Environment(
        loader=jinja2.FileSystemLoader(
          os.path.join(os.path.dirname(__file__),
                     '../views'
          )
        )
      )
      return jinja_environment
